import { OnInit, Injector, Component, Output, ViewChild, ElementRef, EventEmitter } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Base_DataItemServiceProxy } from '@shared/service-proxies/stock-service-proxies';
import { TreeNode, MenuItem } from 'primeng/api';
import { ArrayToTreeConverterService } from '@shared/utils/array-to-tree-converter.service';
import { CreateOrEditDataItemModalComponent } from './create-or-edit-dataitem-modal.component';
import { TreeDataHelperService } from '@shared/utils/tree-data-helper.service';
import * as _ from 'lodash';
import { DataItemDetailsComponent } from './dataitem-details.component';
import { IBasicDataItemInfo } from './basic-dataitem-info';

export interface IBasicDataItemOnTree extends IBasicDataItemInfo {
    id: number;
    parent: string | number;
    code: string;
    displayName: string;
    memberCount: number;
    roleCount: number;
    text: string;
    state: any;
}
@Component({
    selector: 'dataitem-tree',
    templateUrl: './dataitem-tree.component.html'
})
export class DataItemTreeComponent extends AppComponentBase implements OnInit {
    @Output() ouSelected = new EventEmitter<IBasicDataItemInfo>();
    @ViewChild('dataItemDetails') dataItemDetails: DataItemDetailsComponent;
    @ViewChild('createOrEditDataItemModal') createOrEditDataItemModal: CreateOrEditDataItemModalComponent;
    constructor(
        injector: Injector,
        private _baseItemsService: Base_DataItemServiceProxy,
        private _arrayToTreeConverterService: ArrayToTreeConverterService,
        private _treeDataHelperService: TreeDataHelperService
    ) {
        super(injector);
    }

    treeData: any;
    selectedItem: TreeNode;

    itemContextMenuItems: MenuItem[];

    ngOnInit(): void {
        this.itemContextMenuItems = this.getContextMenuItems();
        this.getTreeDataFromServer();
    }

    nodeSelect(event) {
        //this.dataItemDetails.getDataItemDetails(event);
        this.ouSelected.emit(<IBasicDataItemInfo>{
            id: event.node.data.id,
            displayName: event.node.data.displayName
        });
    }

    nodeDrop(event) {}

    reload(event): void {
        this.getTreeDataFromServer();
    }

    private getTreeDataFromServer(): void {
        this._baseItemsService.getDataItems().subscribe(result => {
            this.treeData = this._arrayToTreeConverterService.createTree(
                result.items,
                'parentId',
                'id',
                null,
                'children',
                [
                    {
                        target: 'label',
                        targetFunction(item) {
                            return item.displayName;
                        }
                    },
                    {
                        target: 'expandedIcon',
                        value: 'fa fa-folder-open m--font-warning'
                    },
                    {
                        target: 'collapsedIcon',
                        value: 'fa fa-folder m--font-warning'
                    },
                    {
                        target: 'selectable',
                        value: true
                    }
                ]
            );
        });
    }

    private getContextMenuItems(): any[] {
        //const canManageOrganizationTree = this.isGranted('Pages.Administration.OrganizationUnits.ManageOrganizationTree');

        let items = [
            {
                label: this.l('Edit'),
                // disabled: !canManageOrganizationTree,
                command: event => {
                    if(this.selectedItem.data.code == "marketPurchaseType"){
                        this.notify.warn("此项已被“市采物资管理”引用不能修改");
                        return;
                    }
                    this.createOrEditDataItemModal.show({
                        id: this.selectedItem.data.id,
                        parentId: this.selectedItem.data.parentId,
                        displayName: this.selectedItem.data.displayName,
                        code: this.selectedItem.data.code
                    });
                }
            },
            {
                label: this.l('AddSubUnit'),
                command: () => {
                    this.addUnit(this.selectedItem.data.id);
                }
            },
            {
                label: this.l('Delete'),
                command: () => {
                    if(this.selectedItem.data.id == "23"){
                        this.notify.warn("此项已被“市采物资管理”引用不能删除");
                        return;
                    }
                    this.message.confirm(
                        this.l('删除字典分类', this.selectedItem.data.displayName),
                        this.l('AreYouSure'),
                        isConfirmed => {
                            if (isConfirmed) {
                                this._baseItemsService.deleteDataItem(this.selectedItem.data.id).subscribe(() => {
                                    this.deleteUnit(this.selectedItem.data.id);
                                    this.notify.success(this.l('SuccessfullyDeleted'));
                                    this.selectedItem = null;
                                });
                            }
                        }
                    );
                }
            }
        ];
        return items;
    }

    addUnit(parentId?: number): void {
        this.createOrEditDataItemModal.show({
            parentId: parentId
        });
    }

    deleteUnit(id) {
        let node = this._treeDataHelperService.findNode(this.treeData, { data: { id: id } });
        if (!node) {
            return;
        }

        if (!node.data.parentId) {
            _.remove(this.treeData, {
                data: {
                    id: id
                }
            });
        }

        let parentNode = this._treeDataHelperService.findNode(this.treeData, { data: { id: node.data.parentId } });
        if (!parentNode) {
            return;
        }

        _.remove(parentNode.children, {
            data: {
                id: id
            }
        });
    }
}
